//
//  AppDelegate.m
//  MagicFang
//
//  Created by 华谕 on 2017/11/30.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "AppDelegate.h"
#import "HomePageViewController.h"
#import "HYNavBaseViewController.h"
#import "UMessage.h"
#import <UserNotifications/UserNotifications.h>
#import "IQKeyboardManager.h"

@interface AppDelegate ()<WXApiDelegate, UNUserNotificationCenterDelegate>
@property (nonatomic, strong)NSString *updateurl;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self getapp_Version];
    //初始化方法,也可以使用(void)startWithAppkey:(NSString *)appKey launchOptions:(NSDictionary * )launchOptions httpsenable:(BOOL)value;这个方法，方便设置https请求。
    [UMessage startWithAppkey:@"5a4f4cf98f4a9d03b6000071" launchOptions:launchOptions];
    //注册通知，如果要使用category的自定义策略，可以参考demo中的代码。
    [UMessage registerForRemoteNotifications];
    
    //iOS10必须加下面这段代码。
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate=self;
    UNAuthorizationOptions types10=UNAuthorizationOptionBadge|  UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
    [center requestAuthorizationWithOptions:types10     completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            //点击允许
            //这里可以添加一些自己的逻辑
        } else {
            //点击不允许
            //这里可以添加一些自己的逻辑
        }
    }];
    //打开日志，方便调试
    [UMessage setLogEnabled:YES];
    
    [self initIQKeyboardManager];
    NSString *deviceTokenStr = [LTools cacheForKey:@"deviceToken"];
    if ([LTools storageForKey:SERVER_IsLogin] && deviceTokenStr.length>0) {
        [self requestMessageInit:deviceTokenStr];
    }
    
    [WXApi registerApp:@"wxaa14d376bcf0c83f"];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    HomePageViewController *vc = [[HomePageViewController alloc] init];
    HYNavBaseViewController *nav = [[HYNavBaseViewController alloc] initWithRootViewController:vc];
    self.window.rootViewController = nav;
    
    return YES;
}

- (void)getapp_Version
{
    //获取版本号
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    //版本号信息存到NSUserDefaults沙盒
    [LTools cache:app_Version ForKey:kAppVersion];
    //如果有更新的版本，提醒用户下载
    [self getUpdateInformation];
    
}

- (void)getUpdateInformation
{
    [LTools versionForAppid:@"1346573438" Block:^(BOOL isNewVersion, NSString *updateUrl, NSString *updateContent)
     {
         if (isNewVersion==YES)
         {
             self.updateurl = updateUrl;
             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"印港在线提醒您有新版本" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
             alert.tag = 1015;
             [alert show];
         }
     }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1015)
    {
        if(buttonIndex==1)
        {
            NSURL *url = [NSURL URLWithString:self.updateurl];
            [[UIApplication sharedApplication]openURL:url];
        }
        
    }
}

// 设置IQKeyBoardManager 的一些属性
- (void)initIQKeyboardManager
{
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    // 设置IQKeyBoardManager是否可用
    manager.enable = YES;
    // 点击输入框外面是否需要隐藏键盘
    manager.shouldResignOnTouchOutside = YES;
    // 是否需要显示工具栏
    manager.enableAutoToolbar = NO;
}

// 这个方法是用于从微信返回第三方App
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    
    [WXApi handleOpenURL:url delegate:self];
    
    return YES;
}


// 微信 授权后回调
- (void)onResp:(BaseResp *)resp{
    
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        
    }
    
    if ([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        //        SendMessageToWXResp *sendResp = (SendMessageToWXResp *)resp;
        //
        //        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"分享成功" message:nil delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        //        [alertview show];
        
    }
    if ([resp isKindOfClass:[PayResp class]])
    {
        PayResp *response = (PayResp *)resp;
        switch (response.errCode)
        {
            case WXSuccess:
            {
                [LTools showMBProgressWithText:@"付款成功" addToView:self.window];
                NSNotification * notice = [NSNotification notificationWithName:@"PaySuccess" object:nil];
                //                发送消息
                [[NSNotificationCenter defaultCenter] postNotification:notice];
                break;
            }
                
            default:
            {
                //                [LTools showMBProgressWithText:@"付款失败" addToView:self.window];
                break;
            }
        }
    }
    
    
    
    
}



- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            int resultStatus=[[resultDic objectForKey:@"resultStatus"]intValue];
            if (resultStatus==9000) {
                [LTools showMBProgressWithText:@"付款成功" addToView:self.window];
                NSNotification * notice = [NSNotification notificationWithName:@"PaySuccess" object:nil];
                //发送消息
                [[NSNotificationCenter defaultCenter] postNotification:notice];
            }else{
            }
            
        }];
        return YES;
    }
    
    
    if ([WXApi handleOpenURL:url delegate:self]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}
// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            int resultStatus = [[resultDic objectForKey:@"resultStatus"] intValue];
            
            //支付宝支付成功
            if (resultStatus==9000) {
                [LTools showMBProgressWithText:@"付款成功" addToView:self.window];
                NSNotification * notice = [NSNotification notificationWithName:@"PaySuccess" object:nil];
                //发送消息
                [[NSNotificationCenter defaultCenter] postNotification:notice];
            }
            //支付宝支付失败
            else{
                
            }
            
        }];
        return YES;
    }
    
    if ([WXApi handleOpenURL:url delegate:self]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    
    return YES;
}

//iOS10以下使用这个方法接收通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];
    //关闭U-Push自带的弹出框
    [UMessage setAutoAlert:NO];
    [UMessage didReceiveRemoteNotification:userInfo];
    
//    self.userInfo = userInfo;
//    定制自定的的弹出框
//    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
//    {
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:userInfo[@"aps"][@"alert"][@"title"] message:userInfo[@"aps"][@"alert"][@"body"] delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];
//
//        [alertView show];
//
//    }
}

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];
    NSDictionary * userInfo = notification.request.content.userInfo;
//    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
//    {
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:userInfo[@"aps"][@"alert"][@"title"] message:userInfo[@"aps"][@"alert"][@"body"] delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];
//
//        [alertView show];
//    }
//    if ([LTools storageForKey:SERVER_IsLogin]) {
//        [self requestMessageTest];
//    }
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
        //关闭U-Push自带的弹出框
        [UMessage setAutoAlert:NO];
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        //应用处于前台时的本地推送接受
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        //应用处于后台时的本地推送接受
    }
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSString *error_str = [NSString stringWithFormat: @"%@", error];
    NSLog(@"Failed to get token, error:%@", error_str);
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [UMessage registerDeviceToken:deviceToken];
    NSString *deviceTokenStr = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]                  stringByReplacingOccurrencesOfString: @">" withString: @""]                 stringByReplacingOccurrencesOfString: @" " withString: @""];
    [LTools cache:deviceTokenStr ForKey:@"deviceToken"];
    if ([LTools storageForKey:SERVER_IsLogin]) {
        [self requestMessageInit:deviceTokenStr];
    }
    
    NSLog(@"%@",deviceTokenStr);
}

- (void)requestMessageInit:(NSString *)deviceToken {
//    WEAKSELF;
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestMessageInitParmers:@{@"deviceToken":deviceToken,@"deviceType":@"2"} Success:^(id obj)
     {
//         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
//             [LTools showMBProgressWithText:@"提交成功" addToView:weakSelf.view];
         }
         else
         {
//             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
//         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         
     }];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
